import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../hj_model/cartoon_media_info.dart';
import '../../hj_utils/api_service/acg_service.dart';
import '../../hj_utils/global.dart';
import '../../hj_utils/history_record_util.dart';
import '../../routers/jump_router.dart';
import 'audio_player_bottomsheet.dart';
import 'text_novel_read_page.dart';
import 'voice_novel_read_page.dart';
import 'widget/acg_source_manager.dart';

class NovelDetailLogic extends GetxController {
  String id;
  CartoonMediaInfo? model;
  final recommends = [];
  int page = 1;
  RefreshController? refreshCtr;

  bool showHeader = true;
  double showOffset = 100;

  late ACGSourceManager manager;
  late ScrollController scrollCtr = ScrollController()
    ..addListener(() {
      if (scrollCtr.offset <= showOffset) {
        if (!showHeader) {
          showHeader = true;
          update(['header']);
        }
      } else {
        if (showHeader) {
          showHeader = false;
          update(['header']);
        }
      }
    });
  NovelDetailLogic(this.id) : manager = ACGSourceManager(id);

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
    Future.wait([fetchDetailData(), fetchRecommendData()]).then((value) {
      update();
    });
    //拉取子集
    manager.fetchAllEpisodes();
  }

  Future fetchDetailData() async {
    final result = await ACGService.getMediaInfo(id);
    if (result != null) {
      model = result;
      manager.mediaInfo = result;
      HistoryRecordUtil.insertHistoryModel<CartoonMediaInfo>(model!, HistoryRecordType.novel);
    } else {
      model = CartoonMediaInfo();
    }
  }

  // 获取相关推荐
  Future fetchRecommendData() async {
    final result = await ACGService.comicsRecommendList(page, 12, mediaId: id);
    if (result != null) {
      page += 1;
      recommends.addAll(result.list ?? []);
    }
    result?.hasNext ?? false ? refreshCtr?.loadComplete() : refreshCtr?.loadNoData();
    update();
  }

  // 打开所有章节
  episodesBottomSheet() async {
    final result = await Get.bottomSheet(AudioPlayerBottomSheet(
      model?.title ?? '',
      allAudiobooks: manager.allEpisodes,
      currentPlayIndex: manager.index,
    ));
    if (result != null) {
      gotoPlay(index: result as int);
    }
  }

  gotoPlay({int index = 0}) async {
    final mediaSubType = model?.mediaSubType ?? -1;
    final opm = await manager.getEpisodeHasPermisson(index);
    if (opm != null) {
      manager.changeEpisodesIndex(index);
      //0-默认文本小说 1-有声小说
      if (mediaSubType == 0) {
        Get.to(TextNovelReadPage(manager: manager));
      } else if (mediaSubType == 1) {
        Get.to(
          () => VoiceNovelReadPage(),
          opaque: false,
          arguments: {
            'manager': manager,
            'title': model?.title ?? '',
            'index': index,
            'id': id,
          },
        );
      }
    }
  }

  // 跳转
  jumpToOtherPage(CartoonMediaInfo info) {
    if (model?.id == info.id) {
      showToast('您当前正在观看此媒体');
      return;
    }
    pushToCartoonPage(info);
  }

  // 收藏取消收藏
  collectAction() async {
    final isCollect = model?.mediaStatus?.hasCollected ?? false;
    bool result = false;
    if (isCollect) {
      result = await ACGService.mediaBookshelfDelete(model?.id ?? '');
    } else {
      result = await ACGService.mediaBookshelfAdd(model?.id ?? '');
    }
    if (result) {
      model?.mediaStatus?.hasCollected = !isCollect;
    }
    update();
  }

  //收藏操作
  sendCollection() async {
    bool willColleted = !(model?.mediaStatus?.hasCollected ?? false);
    bool success = false;
    if (willColleted) {
      success = await ACGService.mediaBookshelfAdd(
        model?.id ?? '',
      );
    } else {
      success = await ACGService.mediaBookshelfDelete(model?.id ?? '');
    }
    if (success) {
      model?.mediaStatus?.hasCollected = willColleted;
      if (willColleted) {
        model?.countCollect = (model?.countCollect ?? 0) + 1;
        showToast('已加入书架');
      } else {
        showToast('已移除书架');
        model?.countCollect = (model?.countCollect ?? 1) - 1;
      }
    }
  }
}
